package cn.buk.qms.service;

import cn.buk.common.JsonResult;
import cn.buk.tms.dao.FlightOrderDao;
import cn.buk.tms.entity.bill.BillInfo;
import cn.buk.tms.entity.misc.EntDepartment;
import cn.buk.tms.entity.order.flight.FlightOrder;
import cn.buk.tms.entity.misc.RoleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yfdai
 */
@Service
public class RollbackServiceImpl extends BaseAbstractService implements RollbackService {

  @Autowired
  public RollbackServiceImpl(FlightOrderDao flightOrderDao) {
    this.flightOrderDao = flightOrderDao;
  }

  private final FlightOrderDao flightOrderDao;

  @Override
  @Secured({RoleInfo.ROLE_ADMIN, RoleInfo.ROLE_SUPERVISOR})
  public JsonResult rollbackFlightOrderStatus(final int enterpriseId, final String username, final int orderId, final String remark) {
    // 检查是否有对应的账单，如果有，则不允许回滚
    FlightOrder flightOrder = flightOrderDao.getOrderDetailById(orderId);
    if (flightOrder == null || flightOrder.getEnterpriseId() != enterpriseId) {
      return JsonResult.createJsonResult(-1, "数据错误");
    }

    List<BillInfo> billInfos = billService
            .searchBillInfoByOrderNo(enterpriseId, flightOrder.getOrderNo());
    if (!billInfos.isEmpty()) {
      doSendAlert(enterpriseId, "机票订单(" + flightOrder.getOrderNo() + ")回滚失败，存在对应的账单", null,
              EntDepartment.DEPT_ADMINISTRATOR);
      return JsonResult.createJsonResult(-2, "存在对应的账单，不能回滚");
    }

    // 回滚
    int retCode = flightOrderDao.rollbackFlightOrderStatus(enterpriseId, username, orderId, remark);
    if (retCode > 0) {
      doSendAlert(enterpriseId, "机票订单(" + flightOrder.getOrderNo() + ")已回滚: " + remark, null,
              EntDepartment.DEPT_ADMINISTRATOR);
    }
    return JsonResult.createJsonResult(retCode);
  }
}
